package com.edmendst.xmall.service.impl;

import com.edmendst.xmall.dto.OrderInfo;
import com.edmendst.xmall.dto.OrderItem;
import com.edmendst.xmall.mapper.OrderItemInFoMapper;
import com.edmendst.xmall.mapper.OrdersMapper;
import com.edmendst.xmall.mapper.ProductMapper;
import com.edmendst.xmall.pojo.*;
import com.edmendst.xmall.service.OrderService;
import com.edmendst.xmall.service.ProductService;
import com.edmendst.xmall.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.math.BigDecimal;
import java.sql.Date;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderItemInFoMapper orderItemInFoMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private DefaultTransactionDefinition transactionManager;


    /**
     * 添加订单
     *
     * @param orderInfo
     * @return OrderItem
     */
    @Override
    public OrderItem addOrder(OrderInfo orderInfo) throws JsonProcessingException {
        String lockKey = "order:lock:" + orderInfo.getProductId();
        String lockValue = UUID.randomUUID().toString();
        boolean locked = false;
        try {
            // 尝试获取分布式锁，设置过期时间防止死锁
            locked = Boolean.TRUE.equals(
                    redisTemplate.opsForValue().setIfAbsent(
                            lockKey,
                            lockValue,
                            30,
                            TimeUnit.SECONDS
                    )
            );

            if (!locked) {
                OrderItem orderItem = new OrderItem();
                orderItem.setMessage("系统繁忙，请稍后重试");
                return orderItem;
            }

            // 查询商品库存
            ProductExample productExample = new ProductExample();
            productExample.createCriteria().andProductIdEqualTo(orderInfo.getProductId());
            List<Product> products = productMapper.selectByExample(productExample);
            if (products.isEmpty()) {
                OrderItem orderItem = new OrderItem();
                orderItem.setMessage("商品不存在");
                return orderItem;
            }

            Product product = products.get(0);
            if (product.getProductStock() < orderInfo.getQuantity()) {
                OrderItem orderItem = new OrderItem();
                orderItem.setMessage("库存不足");
                return orderItem;
            }

            // 扣减库存
            int newStock = product.getProductStock() - orderInfo.getQuantity();
            product.setProductStock(newStock);
            productMapper.updateByExampleSelective(product, productExample);

        } finally {
            if (locked) {
                // Lua脚本保证原子性地释放锁
                String luaScript =
                        "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                                "    return redis.call('del', KEYS[1]) " +
                                "else " +
                                "    return 0 " +
                                "end";
                redisTemplate.execute(
                        new DefaultRedisScript<>(luaScript, Long.class),
                        Collections.singletonList(lockKey),
                        lockValue
                );
            }
        }


        Integer userId = userService.selectUserIdByUserName(orderInfo.getUserName());

        // 时间戳+随机数ID
        long timestamp = System.currentTimeMillis();
        String orderId = timestamp + String.valueOf(new Random().nextInt(1000000));

        // 查询商品信息
        Product currentProduct = productMapper.selectByPrimaryKey(orderInfo.getProductId());
        BigDecimal productPrice = currentProduct.getProductPrice();
        String productName = currentProduct.getProductName();
        String productCoverImage = currentProduct.getProductCoverImage();

        // 计算订单总金额
        BigDecimal orderTotalAmount = productPrice.multiply(new BigDecimal(orderInfo.getQuantity()));

        // 创建订单主记录
        Orders order = new Orders();
        order.setOrderId(orderId);
        order.setUserId(userId);
        order.setOrderTotalAmount(orderTotalAmount);
        order.setDeliveryInfo(objectMapper.writeValueAsString(orderInfo.getDeliveryInfo()));
        order.setOrderCreateTime(new Date(timestamp));
        order.setOrderPaymentStatus(false);
        order.setOrderDeliveryStatus(false);
        ordersMapper.insert(order);

        // 创建订单明细
        OrderItemInFo orderItemInfo = new OrderItemInFo();
        orderItemInfo.setOrderId(orderId);
        orderItemInfo.setProductId(orderInfo.getProductId());
        orderItemInfo.setQuantity(orderInfo.getQuantity());
        orderItemInfo.setItemPrice(productPrice);
        orderItemInFoMapper.insert(orderItemInfo);

        // 构造返回结果
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderId(orderId);
        orderItem.setUserId(userId);
        orderItem.setProductPrice(productPrice);
        orderItem.setOrderTotalAmount(orderTotalAmount);
        orderItem.setProductName(productName);
        orderItem.setProductImage(productCoverImage);
        orderItem.setQuantity(orderInfo.getQuantity());
        orderItem.setOrderPaymentStatus(0);
        orderItem.setOrderDeliveryStatus(0);

        return orderItem;
    }


    @Override
    public List<OrderItem> getOrderList(String userName) {
        Integer userIdByUserName = userService.selectUserIdByUserName(userName);

        OrdersExample ordersExample = new OrdersExample();
        ordersExample.createCriteria().andUserIdEqualTo(userIdByUserName);
        List<Orders> orders = ordersMapper.selectByExample(ordersExample);

        List<OrderItem> result = new ArrayList<>();

        if (!orders.isEmpty()) {
            for (Orders order : orders) {
                OrderItemInFoExample orderItemInfoExample = new OrderItemInFoExample();
                orderItemInfoExample.createCriteria().andOrderIdEqualTo(order.getOrderId());
                List<OrderItemInFo> orderItemInfos = orderItemInFoMapper.selectByExample(orderItemInfoExample);

                // 订单项不存在
                if (orderItemInfos.isEmpty()) {
                    continue;
                }

                OrderItemInFo orderItemInfo = orderItemInfos.get(0);

                Product product = productMapper.selectByPrimaryKey(orderItemInfo.getProductId());
                // 商品不存在
                if (product == null) {
                    continue;
                }

                OrderItem orderItem = new OrderItem(
                        order.getOrderId(),
                        userIdByUserName,
                        order.getOrderTotalAmount(),
                        product.getProductName(),
                        orderItemInfo.getQuantity(),
                        Boolean.TRUE.equals(order.getOrderPaymentStatus()) ? 1 : 0,
                        Boolean.TRUE.equals(order.getOrderDeliveryStatus()) ? 1 : 0,
                        Boolean.TRUE.equals(order.getOrderReceivedStatus()) ? 1 : 0,
                        product.getProductCoverImage(),
                        product.getProductId()

                );
                result.add(orderItem);
            }
        }
        return result;
    }

    @Override
    public int deleteOrder(String orderId, String userName) {
        if (userService.selectUserIdByUserName(userName) == ordersMapper.selectByPrimaryKey(orderId).getUserId()) {
            //恢复库存
            OrderItemInFoExample order_itemExample = new OrderItemInFoExample();
            order_itemExample.createCriteria().andOrderIdEqualTo(orderId);
            Integer quantity = orderItemInFoMapper.selectByExample(order_itemExample).get(0).getQuantity();
            Integer productId = orderItemInFoMapper.selectByExample(order_itemExample).get(0).getProductId();
            ProductExample productExample = new ProductExample();
            productExample.createCriteria().andProductIdEqualTo(productId);
            Integer productStock = productMapper.selectByExample(productExample).get(0).getProductStock();
            productStock += quantity;
            Product product = new Product();
            product.setProductStock(productStock);
            int i = productMapper.updateByExampleSelective(product, productExample);
            //删除订单
            int delete1 = orderItemInFoMapper.deleteByExample(order_itemExample);
            int delete = ordersMapper.deleteByPrimaryKey(orderId);

            if (delete == 1 && delete1 == 1 && i == 1) {
                return 1;
            }
        }
        return 0;
    }



    @Override
    public List<OrderItem> getOrderListByShop(Integer shopId) {
        List<OrderItem> orderItems = ordersMapper.selectOrderListByShop(shopId);
        List<OrderItem> result = new ArrayList<>();
        for (OrderItem orderItem : orderItems) {
            for (OrderItem.OrderItemDetail itemDetail : orderItem.getItems()) {
                OrderItem orderItem1 = new OrderItem();
                orderItem1.setOrderId(orderItem.getOrderId());
                orderItem1.setUserId(orderItem.getUserId());
                orderItem1.setProductPrice(orderItem.getProductPrice());
                orderItem1.setProductName(itemDetail.getProductName());
                orderItem1.setQuantity(itemDetail.getQuantity());
                orderItem1.setOrderPaymentStatus(orderItem.getOrderPaymentStatus());
                orderItem1.setOrderDeliveryStatus(orderItem.getOrderDeliveryStatus());
                orderItem1.setOrderReceivedStatus(orderItem.getOrderReceivedStatus());
                orderItem1.setProductImage(itemDetail.getProductCoverImage());
                result.add(orderItem1);
            }
        }
        return result;
    }

    @Override
    public int updateOrderDeliveryStatus(String orderId, Integer orderDeliveryStatus) {
       if (orderDeliveryStatus == 1){
           OrdersExample ordersExample = new OrdersExample();
           ordersExample.createCriteria().andOrderIdEqualTo(orderId);

           Orders orders = new Orders();
           orders.setOrderDeliveryStatus(true);

           int i = ordersMapper.updateByExampleSelective(orders, ordersExample);
           return i;
       }
       return 0;
    }

    @Override
    public int updateOrderReceivedStatus(String orderId, Integer orderReceivedStatus) {
        if (orderReceivedStatus == 1){
            OrdersExample orderExample = new OrdersExample();
            orderExample.createCriteria().andOrderIdEqualTo(orderId);
            Orders orders = new Orders();
            orders.setOrderReceivedStatus(true);
            int i = ordersMapper.updateByExampleSelective(orders, orderExample);
            return i;
        }
        return 0;
    }

    @Override
    public OrderItem getOrderDetail(String orderId) {
        OrdersExample orderExample = new OrdersExample();
        orderExample.createCriteria().andOrderIdEqualTo(orderId);
        Orders order = ordersMapper.selectByExampleWithBLOBs(orderExample).get(0);   // 使用包含BLOB的映射

        OrderItemInFoExample order_itemExample = new OrderItemInFoExample();
        order_itemExample.createCriteria().andOrderIdEqualTo(orderId);
        OrderItemInFo order_item = orderItemInFoMapper.selectByExample(order_itemExample).get(0);

        String productName = productService.getProductById(order_item.getProductId()).getProductName();
        String productCoverImage = productService.getProductById(order_item.getProductId()).getProductCoverImage();

        if (order != null && order_item != null) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getOrderId());
            orderItem.setUserId(order.getUserId());
            orderItem.setProductPrice(order.getOrderTotalAmount());
            orderItem.setProductName(productName);
            orderItem.setProductImage(productCoverImage);
            orderItem.setQuantity(order_item.getQuantity());
            orderItem.setOrderPaymentStatus(order.getOrderPaymentStatus() ? 1 : 0);
            orderItem.setOrderDeliveryStatus(order.getOrderDeliveryStatus() ? 1 : 0);
            orderItem.setOrderTrackingNumber(order.getOrderTrackingNumber());
            orderItem.setOrderCreateTime(order.getOrderCreateTime().toString());
            orderItem.setDeliveryInfo(order.getDeliveryInfo());
            orderItem.setOrderTotalAmount(order.getOrderTotalAmount());
            return orderItem;
        }
        return null;
    }


}
//    private String userName;
//    private Integer productId;
//    private Integer quantity;
//    private DeliveryInfo deliveryInfo;
//    @Override
//    public OrderItem addOrder(OrderInfo orderInfo) throws JsonProcessingException {
//        ProductExample productExample = new ProductExample();
//        productExample.createCriteria().andProductIdEqualTo(orderInfo.getProductId());
//
//        Integer productStock = productMapper.selectByExample(productExample).get(0).getProductStock();
//        if (productStock < orderInfo.getQuantity()) {
//            OrderItem orderItem = new OrderItem();
//            orderItem.setMessage("库存不足");
//            System.out.println("库存不足");
//            return orderItem;
//        }
//        //减少库存
//        productStock -= orderInfo.getQuantity();
//        Product product = new Product();
//        product.setProductStock(productStock);
//        productMapper.updateByExampleSelective(product, productExample);
//
//        Integer userId = userService.selectUserIdByUserName(orderInfo.getUserName());
//
//        //获取时间戳(毫秒级)
//        Long time = System.currentTimeMillis();
//        //随机数
//        Random random = new Random();
//        String orderId = String.valueOf(time + random.nextInt(1000000));
//
//        BigDecimal productPrice = productMapper.selectByExample(productExample).get(0).getProductPrice();
//        String productName = productMapper.selectByExample(productExample).get(0).getProductName();
//        String productCoverImage = productMapper.selectByExample(productExample).get(0).getProductCoverImage();
//
//
//        BigDecimal orderTotalAmount = productPrice.multiply(new BigDecimal(orderInfo.getQuantity()));
//
//        /**
//         *         order_id	VARCHAR(32)	主键	-	订单号（时间戳+随机数）
//         *         user_id	INT UNSIGNED	外键（引用 user）	-	用户ID
//         *         order_total_amount	DECIMAL(10,2) UNSIGNED	非空	-	订单总金额
//         *         delivery_info JSON NOT NULL COMMENT '完整配送信息快照',
//         *                 receiver_phone VARCHAR(20) GENERATED ALWAYS AS (JSON_UNQUOTE(delivery_info->'$.mobile')) VIRTUAL COMMENT '虚拟列-收件电话',
//         *                 ADD INDEX idx_receiver_phone (receiver_phone);
//         *         order_id	VARCHAR(32)	外键（引用 order）	-	订单号
//         *         product_id	INT UNSIGNED	外键（引用 product）	-	商品ID
//         *         quantity	INT UNSIGNED	非空	-	商品数量
//         *         item_price	DECIMAL(10,2) UNSIGNED	非空	-	下单时价格
//         */
//
//        Orders order = new Orders();
//        order.setOrderId(orderId);
//        order.setUserId(userId);
//        order.setOrderTotalAmount(orderTotalAmount);
////        order.setDeliveryInfo(orderInfo.getDeliveryInfo().toString());
//        String deliveryJson = objectMapper.writeValueAsString(orderInfo.getDeliveryInfo());
//        order.setDeliveryInfo(deliveryJson);
//        order.setOrderCreateTime(new Date(time));
//        order.setOrderPaymentStatus(false);
//        order.setOrderDeliveryStatus(false);
//
//        int insert = ordersMapper.insert(order);
//
//        OrderItemInFo order_item = new OrderItemInFo();
//        order_item.setOrderId(orderId);
//        order_item.setProductId(orderInfo.getProductId());
//        order_item.setQuantity(orderInfo.getQuantity());
//        order_item.setItemPrice(productPrice);
//
//        int insert1 = orderItemInFoMapper.insert(order_item);
//
//        /**
//         *    //返回字段
//         *             private String orderId;
//         *             private Integer userId;
//         *             private BigDecimal productPrice;
//         *             private String productName;
//         *             private Integer quantity;
//         *             private Integer orderPaymentStatus;
//         *             private Integer orderDeliveryStatus;
//         *             private  String errorMessage;
//         *             private String orderTrackingNumber;
//         *             private String orderCreateTime;
//         *             private String deliveryInfo;
//         *             private BigDecimal orderTotalAmount;
//         */
//
//
//        if (insert == 1 && insert1 == 1) {
//            OrderItem orderItem = new OrderItem();
//            orderItem.setOrderId(orderId);
//            orderItem.setUserId(userId);
//            orderItem.setProductPrice(productPrice);
//            orderItem.setOrderTotalAmount(orderTotalAmount);
//            orderItem.setProductName(productName);
//            orderItem.setProductImage(productCoverImage);
//            orderItem.setQuantity(orderInfo.getQuantity());
//            orderItem.setOrderPaymentStatus(0);
//            orderItem.setOrderDeliveryStatus(0);
//
//            return orderItem;
//        }
//        return null;
//    }